﻿//**********************************************************
//Copyright(C)2010 By 波特商网公司 版权所有。
//
//文件名：
//文件功能：TextBox自定义控件
//
//创建标识： 米海波 || 2011-04-01
//
//修改标识：1.追加是否启用Enter模拟Tab 属性EnterKeyAsSendTab，默认启用 
//           陈博生 || 2011-06-03
//修改描述：
//**********************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace Hmc.IM.Common.UserControls
{
    /// <summary>
    /// 扩展的TextBox
    /// </summary>
    [System.ComponentModel.DefaultProperty("Expression")]
    public partial class ucTextBox : TextBox, IValidate
    {

        /// <summary> 
        /// 是否启用热点效果 
        /// </summary> 
        private bool _HotTrack = true;

        /// <summary> 
        /// 边框颜色 
        /// </summary> 
        private Color _BorderColor = Color.FromArgb(219, 224, 230);

        /// <summary> 
        /// 热点边框颜色 
        /// </summary> 
        private Color _HotColor = Color.FromArgb(0x33, 0x5E, 0xA8);

        /// <summary> 
        /// 是否鼠标MouseOver状态 
        /// </summary> 
        private bool _IsMouseOver = false;


        #region 属性


        #region 按Enter是否模拟TAB   陈博生   2011-06-03
        private bool _enterKeyAsSendTab = true;

        /// <summary>
        /// 按Enter是否模拟TAB
        /// </summary>
        [Category("行为"), Browsable(true), Description("按Enter是否模拟TAB")]
        public bool EnterKeyAsSendTab
        {
            get { return _enterKeyAsSendTab; }
            set { _enterKeyAsSendTab = value; }
        }
        #endregion

        /// <summary> 
        /// 是否启用热点效果 
        /// </summary> 
        [Category("行为"),
       Description("获得或设置一个值，指示当鼠标经过控件时控件边框是否发生变化。只在控件的BorderStyle为FixedSingle时有效"),
       DefaultValue(true)]
        public bool HotTrack
        {
            get
            {
                return this._HotTrack;
            }
            set
            {
                this._HotTrack = value;
                //在该值发生变化时重绘控件，下同 
                //在设计模式下，更改该属性时，如果不调用该语句， 
                //则不能立即看到设计试图中该控件相应的变化 
                this.Invalidate();
            }
        }
        /// <summary> 
        /// 边框颜色 
        /// </summary> 
        [Category("外观"),
       Description("获得或设置控件的边框颜色"),
       DefaultValue(typeof(Color), "219, 224, 230")]
        public Color BorderColor
        {
            get
            {
                return this._BorderColor;
            }
            set
            {
                this._BorderColor = value;
                this.Invalidate();
            }
        }
        /// <summary> 
        /// 热点时边框颜色 
        /// </summary> 
        [Category("外观"),
       Description("获得或设置当鼠标经过控件时控件的边框颜色。只在控件的BorderStyle为FixedSingle时有效"),
       DefaultValue(typeof(Color), "#335EA8")]
        public Color HotColor
        {
            get
            {
                return this._HotColor;
            }
            set
            {
                this._HotColor = value;
                this.Invalidate();
            }
        }

        /// <summary>
        /// 设置验证未通过时是否保持焦点
        /// </summary>
        [Browsable(true), Category("验证"), Description("设置验证未通过时是否保持焦点")]
        public keepFocus KeepFocus
        {
            get { return _keepFocus; }
            set
            {
                _keepFocus = value;
            }

        }

        /// <summary>
        /// 获取该控件是否已验证通过
        /// </summary>
        [Browsable(false), Category("验证"), Description("获取该控件是否已验证通过")]
        public bool IsValidated
        {
            get { return isValidated; }
            set { isValidated = value; }
        }
        /// <summary>
        /// 设置控件的值是否允许为空
        /// </summary>
        [Browsable(true), Category("验证"), DefaultValue(true), Description("设置控件的值是否允许为空")]
        public bool IsAllowEmpty
        {
            get { return isAllowEmpty; }
            set
            {
                isAllowEmpty = value;
                if (!isAllowEmpty)
                {
                    this.SetError = "该项不能为空！";
                }
            }
        }

        /// <summary>
        /// 验证类型
        /// </summary>
        [Browsable(true), Category("验证"), Description("选择验证类型")]
        public TextBoxValidateType ValidateType
        {
            get { return _type; }
            set
            {
                _type = value;

                string verrorText = string.Empty;
                string resultText = string.Empty;

                this.Expression = GetValidateExpression(value, ref verrorText);
                if (this.ReadOnly)
                {
                    expression = string.Empty;
                }
                if (!this.ReadOnly && this.setError == string.Empty)
                {
                    this.setError = verrorText;
                }
            }
        }

        /// <summary>
        /// 设置要匹配的正则表达式
        /// </summary>
        [Browsable(true), Category("验证"), Description("设置要匹配的正则表达式")]
        public string Expression
        {
            get { return expression; }
            set { expression = value; }
        }
        /// <summary>
        /// 设置验证未通过时提示的内容
        /// </summary>
        [Browsable(true), Category("验证"), Description("设置验证未通过时提示的内容")]
        public string SetError
        {
            get { return setError; }
            set { setError = value; }
        }
        /// <summary>
        /// 设置单击控件时是否全选其文本
        /// </summary>
        [Browsable(true), Category("验证"), DefaultValue(true), Description("设置单击控件时是否全选其文本")]
        public bool IsSelectAll
        {
            get { return isSelectAll; }
            set { isSelectAll = value; }
        }
        /// <summary>
        /// 获取和设置此控件的全选状态
        /// </summary>
        [Browsable(false), Category("验证"), DefaultValue(true), Description("获取和设置此控件的全选状态")]
        public bool SelectAlled
        {
            get { return selectAlled; }
            set { selectAlled = value; }
        }
        /// <summary>
        /// 设置错误提示的样式
        /// </summary>
        [Browsable(true), Category("验证"), Description("设置错误提示的样式")]
        public errorView ErrorView
        {
            get { return _errorView; }
            set
            {
                _errorView = value;
            }
        }

        #region 默认文字提示功能 陈博生（2011-5-17）

        #region 表层文字
        private string _emptyTextTip = string.Empty;

        /// <summary>
        /// 
        /// </summary>
        [Category("外观"), Browsable(true), Description("表层文字")]
        public string EmptyTextTip
        {
            get { return _emptyTextTip; }
            set { _emptyTextTip = value; }
        }
        #endregion

        #region 表层文字颜色
        private Color _emptyTextTipColor = Color.DarkGray;

        /// <summary>
        /// 
        /// </summary>
        [Category("外观"),Browsable(true),Description("表层文字颜色"),DefaultValue(typeof(Color), "DarkGray")]
        public Color EmptyTextTipColor
        {
            get { return _emptyTextTipColor; }
            set { _emptyTextTipColor = value; }
        }
        #endregion

        #endregion

        #endregion 属性

        /// <summary>
        /// 验证未通过时是否保持焦点;
        /// </summary>
        public enum keepFocus
        {
            /// <summary>
            /// 否
            /// </summary>
            False,
            /// <summary>
            /// 是
            /// </summary>
            True
        }
        /// <summary>
        /// 设置错误提示的样式;
        /// </summary>
        public enum errorView
        {
            /// <summary>
            /// 图标
            /// </summary>
            OnlyIco, 
            /// <summary>
            /// 文字
            /// </summary>
            OnlyText, 

            /// <summary>
            /// ToolTip显示
            /// </summary>
            OnlyTip,
            /// <summary>
            /// 两者同时
            /// </summary>
            Both
        }

        /// <summary>
        /// 验证类型
        /// </summary>
        public enum TextBoxValidateType
        {
            /// <summary>
            /// 整数
            /// </summary>
            Int,
            /// <summary>
            /// 数量
            /// </summary>
            Qty,
            /// <summary>
            /// 价格
            /// </summary>
            Price,
            /// <summary>
            /// 金额
            /// </summary>
            Amount,
            /// <summary>
            /// 邮编
            /// </summary>
            PostCode,
            /// <summary>
            /// 邮件
            /// </summary>
            Email,
            /// <summary>
            /// 固话
            /// </summary>
            TelPhone,
            /// <summary>
            /// 移动电话
            /// </summary>
            MobilePhone,
            /// <summary>
            /// 身份证
            /// </summary>
            IdentificationCard,
            /// <summary>
            /// 网址
            /// </summary>
            Url,
            /// <summary>
            /// 数据
            /// </summary>
            Date,
            /// <summary>
            /// 时间
            /// </summary>
            Time,
            /// <summary>
            /// 自定义
            /// </summary>
            Cutoms
        }

        private keepFocus _keepFocus = keepFocus.False;
        private TextBoxValidateType _type = TextBoxValidateType.Cutoms;
        private bool isValidated;//获取该控件是否已验证通过;
        private bool isAllowEmpty = true;//设置控件的值是否允许为空;
        private string expression = "";//设置要匹配的正则表达式;
        private string setError = "";//验证未通过时提示的内容;
        private bool isSelectAll = true;//设置单击控件时是否全选其文本;
        private bool selectAlled = false;//获取和设置此控件的全选状态;
        private ucErrorProvider err = new ucErrorProvider();
        private System.Windows.Forms.Label label = new System.Windows.Forms.Label();
        /// <summary>
        /// Tip提示
        /// </summary>
        private ToolTip tip = new ToolTip();

        private errorView _errorView = errorView.OnlyIco;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ucTextBox()
        {
            if (!DesignMode)
            {
                tip.IsBalloon = true;
                this.BorderStyle = BorderStyle.FixedSingle;
                this.ForeColor = Color.FromArgb(115, 115, 115);
                if (this.ReadOnly)
                {
                    this.BorderStyle = BorderStyle.None;
                }
                this.Disposed += new EventHandler(ucTextBox_Disposed);
            }
        }

        void ucTextBox_Disposed(object sender, EventArgs e)
        {
            err.Dispose();
            label.Dispose();
            tip.Dispose();
            GC.Collect();
        }

        #region 事件 方法

        /// <summary>
        /// 获取验证的正则格式
        /// </summary>
        /// <param name="type"></param>
        /// <param name="errorText"></param>
        /// <returns></returns>
        private string GetValidateExpression(TextBoxValidateType type, ref string errorText)
        {
            string result = string.Empty;

            if (!this.ReadOnly)
            {
                switch (type)
                {
                    case TextBoxValidateType.Amount:   //两位小数
                        result = "^[0-9]{1,9}(.[0-9]{1,2})?$";
                        errorText = "无效的金额格式!";
                        break;
                    case TextBoxValidateType.Price:
                        result = "^[0-9]+(.[0-9]{6})?$";
                        errorText = "无效的价格格式!";
                        break;
                    case TextBoxValidateType.Qty:
                        result = @"^[0-9]*$";
                        errorText = "无效的数量格式!";
                        break;
                    case TextBoxValidateType.Email:
                        result = @"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$";
                        errorText = "无效的邮件地址!";
                        break;
                    case TextBoxValidateType.IdentificationCard:
                        result = @"^\d{18}$";//\d{15}|
                        errorText = "无效的身份证件!";
                        break;
                    case TextBoxValidateType.Int:
                        result = @"^-?\d+$";
                        errorText = "无效的整数!";
                        break;
                    case TextBoxValidateType.MobilePhone:
                        result = @"^((\(\d{3}\))|(\d{3}\-))?13[0-9]\d{8}|15[0-9]\d{8}|18[0-9]\d{8}";
                        errorText = "无效的手机号码!";
                        break;
                    case TextBoxValidateType.TelPhone:
                        result = @"^[0-9]{3,4}-[0-9]{6,8}|1[0-9]{10}$";
                        errorText = "正确格式010-123456！";
                        break;
                    case TextBoxValidateType.PostCode:
                        result = @"^\d{6}$";
                        errorText = "无效的邮政编码!";
                        break;
                    case TextBoxValidateType.Url:
                        result = @"^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$";
                        errorText = "无效的网址![http://www.szporter.com]";
                        break;
                    case TextBoxValidateType.Cutoms:
                        result = "";
                        if (expression != string.Empty)
                        {
                            result = expression;
                        }
                        errorText = this.setError;
                        break;
                    default:
                        break;
                }
            }
            return result;
        }

        /// <summary>
        /// 重写控件获取焦点事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnEnter(EventArgs e)
        {
            if (_errorView == errorView.OnlyTip)
            {
                tip.RemoveAll();
            }
            base.OnEnter(e);
        }

        /*
         * 设置属性默认值
         * 1.对于简单属性，使用DefaultValue()；
         * 2.对于复杂属性，使用Reset<属性名>,ShouldSerialize<属性名>来设置，VS只能识别这种命名格式的方法
         * 设置了默认值，就应该相应的初始化这些属性
         */
        /// <summary>
        /// 
        /// </summary>
        public void ResetKeepFocus()
        {
            KeepFocus = keepFocus.False;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool ShouldSerializeKeepFocus()
        {
            return KeepFocus != keepFocus.False;
        }
        /// <summary>
        /// 重置错误显示
        /// </summary>
        public void ResetErrorView()
        {
            ErrorView = errorView.OnlyIco;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool ShouldSerializeErrorView()
        {
            return ErrorView != errorView.OnlyIco;
        }

        /// <summary>
        /// 验证数据
        /// </summary>
        /// <param name="e"></param>
        protected override void OnValidating(CancelEventArgs e)
        {
            ucTextBox t = (ucTextBox)this;
            t.SelectAlled = false;

            if (this.ReadOnly || (isAllowEmpty && t.Text.Trim() == string.Empty))
            {
                //无需匹配正则表达式
                isValidated = true;
                err.Clear();
                this.Parent.Controls.Remove(label);
                return;
            }

            if ((!isAllowEmpty && t.Text.Trim() == "") || !System.Text.RegularExpressions.Regex.IsMatch(t.Text, expression))
            {
                isValidated = false;

                if (_errorView == errorView.OnlyIco)
                {
                    IcoView(t);
                }
                else if (_errorView == errorView.OnlyText)
                {
                    TextView(t, 2);
                }
                else if (_errorView == errorView.OnlyTip)
                {
                    TipView(t);
                }
                else if (_errorView == errorView.Both)
                {
                    IcoView(t);
                    TextView(t, 2);
                }

                if (_keepFocus == keepFocus.True)
                {
                    e.Cancel = true;
                }
            }
            else
            {
                isValidated = true;
                err.Clear();
                this.Parent.Controls.Remove(label);
                //err.SetError(this, "");
            }
            base.OnValidating(e);
        }

        /// <summary>
        /// 键盘按下事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnKeyDown(KeyEventArgs e)
        {
            if (!this.Multiline && e.KeyCode == Keys.Enter && _enterKeyAsSendTab)
            {
                SendKeys.Send("{TAB}");
            }
            base.OnKeyDown(e);
        }

        /// <summary>
        /// 手动调用验证
        /// </summary>
        public void Checking()
        {
            OnValidating(new CancelEventArgs());
        }

        /// <summary>
        /// 显示ErrorProvider错误提示
        /// </summary>
        /// <param name="t"></param>
        private void IcoView(ucTextBox t)
        {
            //err.SetIconAlignment(t, ErrorIconAlignment.MiddleRight);
            //err.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.AlwaysBlink;//错误图标一直闪烁，在这种情况下鼠标指上去的时候错误提示不会消失
            //err.SetIconPadding(t, 3);
            if ((!isAllowEmpty && t.Text.Trim() == ""))
            {
                err.SetError(t, "该项不能为空！");
            }
            else
            {
                err.SetError(t, setError == "" ? " " : setError);
            }
        }
        /// <summary>
        /// 显示Label错误提示
        /// </summary>
        /// <param name="t"></param>
        /// <param name="pointX"></param>
        private void TextView(ucTextBox t, int pointX)
        {
            int x = t.Location.X + t.Size.Width + pointX;
            int y = t.Location.Y + 6;
            Point p = new Point(x, y);

            label.AutoSize = true;
            label.ForeColor = System.Drawing.Color.Red;
            label.Font = new System.Drawing.Font("宋体", 10F);
            label.BackColor = System.Drawing.Color.Transparent;
            label.Location = p;
            label.Text = setError;
            t.Parent.Controls.Add(label);
        }

        /// <summary>
        /// Tip显示
        /// </summary>
        /// <param name="t"></param>
        private void TipView(ucTextBox t)
        {
            string errorMsg = string.Empty;
            if (!isAllowEmpty && t.Text.Trim() == string.Empty)
            {
                errorMsg = "该项不能为空！";
            }
            else
            {
                errorMsg = setError == "" ? " " : setError;
            }
            tip.Active = false;
            tip.SetToolTip(t, errorMsg);
            tip.Active = true;
            tip.Show(errorMsg, t, t.Width / 2, t.Height / 2);
        }

        /// <summary>
        /// 重写Click事件
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClick(EventArgs e)
        {
            if (!this.SelectAlled && IsSelectAll)
            {
                this.SelectAll();
                this.SelectAlled = true;
            }
            base.OnClick(e);
        }
        /// <summary>
        /// 重新绘制
        /// </summary>
        /// <param name="pe"></param>
        protected override void OnPaint(PaintEventArgs pe)
        {
            // TODO: 在此处添加自定义绘制代码

            // 调用基类 OnPaint
            base.OnPaint(pe);
        }

        /// <summary> 
        /// 鼠标移动到该控件上时 
        /// </summary> 
        /// <param name="e"></param> 
        protected override void OnMouseMove(MouseEventArgs e)
        {
            //鼠标状态 
            this._IsMouseOver = true;
            if (this._HotTrack)
            {
                //重绘 
                this.Invalidate();
            }
            base.OnMouseMove(e);
        }
        /// <summary> 
        /// 当鼠标从该控件移开时 
        /// </summary> 
        /// <param name="e"></param> 
        protected override void OnMouseLeave(EventArgs e)
        {
            this._IsMouseOver = false;

            if (this._HotTrack)
            {
                //重绘 
                this.Invalidate();
            }
            base.OnMouseLeave(e);
        }

        /// <summary> 
        /// 当该控件获得焦点时 
        /// </summary> 
        /// <param name="e"></param> 
        protected override void OnGotFocus(EventArgs e)
        {

            if (this._HotTrack)
            {
                //重绘 
                this.Invalidate();
            }
            base.OnGotFocus(e);
        }
        /// <summary> 
        /// 当该控件失去焦点时 
        /// </summary> 
        /// <param name="e"></param> 
        protected override void OnLostFocus(EventArgs e)
        {
            if (this._HotTrack)
            {
                //重绘 
                this.Invalidate();
            }
            base.OnLostFocus(e);
        }

        /// <summary> 
        /// 获得操作系统消息 
        /// </summary> 
        /// <param name="m"></param> 
        protected override void WndProc(ref Message m)
        {

            base.WndProc(ref m);
            if (m.Msg == NativeMethods.WM_PAINT
                || m.Msg == NativeMethods.WM_CTLCOLOREDIT)
            {
                //拦截系统消息，获得当前控件进程以便重绘。 
                //一些控件（如TextBox、Button等）是由系统进程绘制，重载OnPaint方法将不起作用. 
                //所有这里并没有使用重载OnPaint方法绘制TextBox边框。 
                // 
                //MSDN:重写 OnPaint 将禁止修改所有控件的外观。 
                //那些由 Windows 完成其所有绘图的控件（例如 Textbox）从不调用它们的 OnPaint 方法， 
                //因此将永远不会使用自定义代码。请参见您要修改的特定控件的文档， 
                //查看 OnPaint 方法是否可用。如果某个控件未将 OnPaint 作为成员方法列出， 
                //则您无法通过重写此方法改变其外观。 
                // 
                //MSDN:要了解可用的 Message.Msg、Message.LParam 和 Message.WParam 值， 
                //请参考位于 MSDN Library 中的 Platform SDK 文档参考。可在 Platform SDK（“Core SDK”一节） 
                //下载中包含的 windows.h 头文件中找到实际常数值，该文件也可在 MSDN 上找到。 
                IntPtr hDC = NativeMethods.GetWindowDC(m.HWnd);
                if (hDC.ToInt32() == 0)
                {
                    return;
                }

                //只有在边框样式为FixedSingle时自定义边框样式才有效 
                if (this.BorderStyle == BorderStyle.FixedSingle)
                {
                    System.Drawing.Pen pen;

                    //边框Width为1个像素 
                    pen = new Pen(this._BorderColor, 1); ;

                    if (this._HotTrack)
                    {
                        if (this.Focused)
                        {
                            pen.Color = this._HotColor;
                        }
                        else
                        {
                            if (this._IsMouseOver)
                            {
                                pen.Color = this._HotColor;
                            }
                            else
                            {
                                pen.Color = this._BorderColor;
                            }
                        }
                    }
                    //绘制边框 
                    using (Graphics g = Graphics.FromHwnd(this.Handle))
                    {
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
                        pen.Dispose();
                    }
                }

                if (BorderStyle == BorderStyle.None)
                {
                    using (Graphics g = Graphics.FromHwnd(this.Handle))
                    {

                        System.Drawing.Pen pen = new Pen(this.BackColor, 2);
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.DrawLine(pen, 0, this.Height, this.Width, this.Height);
                        pen.Dispose();
                    }
                }

                //默认文字提示  陈博生 2011年5月17日 
                if (m.Msg == 0xf)
                {
                    WmEmptyTextPaint(ref m);
                }

                //返回结果 
                m.Result = IntPtr.Zero;
                //释放 
                NativeMethods.ReleaseDC(m.HWnd, hDC);
            }
        }

        /// <summary>
        /// 默认文字提示
        /// </summary>
        /// <param name="m">windows消息</param>
        private void WmEmptyTextPaint(ref Message m)
        {
            using (Graphics graphics = Graphics.FromHwnd(m.HWnd))
            {
                if (Text.Length == 0
                    && !string.IsNullOrEmpty(_emptyTextTip)
                    && !Focused)
                {
                    TextFormatFlags format =
                        TextFormatFlags.EndEllipsis |
                        TextFormatFlags.VerticalCenter;

                    if (RightToLeft == RightToLeft.Yes)
                    {
                        format |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
                    }

                    TextRenderer.DrawText(
                        graphics,
                        _emptyTextTip,
                        Font,
                        base.ClientRectangle,
                        _emptyTextTipColor,
                        format);
                }
            }
        }

        #endregion

        
        /// <summary>
        /// 触发验证并返回验证结果
        /// </summary>
        /// <returns></returns>
        public bool Validate()
        {
            OnValidating(new CancelEventArgs());
            return IsValidated;
        }

    }
}
